import requests
import json


# {'status': '1', 'regeocode': {'addressComponent': 
#               {'city': '齐齐哈尔市', 'province': '黑龙江省', 'adcode': '230202', 'district': '龙沙区', 
#                'towncode': '230202004000', 'streetNumber': {'number': '14号', 'location': '123.956810,47.339764',
#                  'direction': '西北', 'distance': '32.3657', 'street': '卜奎南大街'}, 
# 'country': '中国', 'township': '正阳街道', 'businessAreas': [[]], 'building': {'name': [], 'type': []}, 'neighborhood': {'name': [], 'type': []}, 'citycode': '0452'}, 'formatted_address': '黑龙江省齐齐哈尔市龙沙区正阳街道卜奎南大街迈特 广场(卜奎南大街店)'}, 'info': 'OK', 'infocode': '10000'}
def geocode(location):
        parameters = {'location': location, 'key': 'ae30ded5e9664a6ae45c9b58915dc84b'}
        base = 'http://restapi.amap.com/v3/geocode/regeo'
        response = requests.get(base, parameters)
        answer = response.json()
        # answer['regeocode']['formatted_address']
        province = answer['regeocode']['addressComponent']['province']
        city = answer['regeocode']['addressComponent']['city']
        district = answer['regeocode']['addressComponent']['district']
        return province,city,district
        # return answer

# 高德开放平台API服务
def gaode_map_api(api_name, api_params):
    # 高德API服务的URL
    base_url = "http://restapi.amap.com/v3/"
    # 高德API服务的Key
    api_key = "ae30ded5e9664a6ae45c9b58915dc84b"
 
    # 拼接完整的请求URL
    url = base_url + api_name + "?key=" + api_key
    for param in api_params:
        url += "&" + param + "=" + api_params[param]
 
    # 发送HTTP GET请求
    response = requests.get(url)
    if response.status_code == 200:
        # 解析JSON格式的响应数据
        return json.loads(response.text)
    else:
        return "Error: " + str(response.status_code)
 
# 调用高德API服务进行逆地理编码查询
def get_address_by_location(location):
    # 逆地理编码API
    api_name = "geocode/regeo"
    # 构建请求参数
    api_params = {
        "location": location,
        "radius": "1000",
        "extensions": "all",
    }
    # 发起API请求
    response = gaode_map_api(api_name, api_params)
    # 提取地址信息
    if "regeocode" in response and "formatted_address" in response["regeocode"]:
        return response["regeocode"]["formatted_address"]
    else:
        return "Error: 无法获取地址信息"
 
# 使用示例
# location = "116.397428,39.90923"  # 北京天安门的经纬度
location = "123.957106,47.339553"  
# address = get_address_by_location(location)
address = geocode(location)
print(address)